﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
using TwitterStatisticsModel;

namespace App_Code
{
    /// <summary>
    ///Has one public method, that allows getting all tweets from a correct Twitter Search API Json response
    /// </summary>
    public static class JsonTwitterParser
    {
        private static string searchApi = @"http://search.twitter.com/search.json";
        /// <summary>
        /// Get all tweets that are returned by response on search by given keyword
        /// </summary>
        /// <param name="keyword">Keyword</param>
        /// <returns>All tweets by given keyword</returns>
        public static List<TweetStored> GetTweets(string keyword)
        {
            string url = searchApi + "?q=" + Uri.EscapeUriString(keyword) + @"&result_type=mixed";
            List<TweetStored> tweets = new List<TweetStored>();
            while (true)
            {
                string json;
                try
                {
                    json = GetJson(url);
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                JObject jObject = JObject.Parse(json);
                string nextPageUrl = (string) jObject["next_page"];
                if (GetNextPage(nextPageUrl, out url))
                {
                    break;
                }
                JArray results = (JArray) jObject["results"];
                foreach (JObject result in results)
                {
                    tweets.Add(GetTweet(result));
                }
            }
            return tweets;
        }

        private static bool GetNextPage(string nextPageUrl, out string url)
        {
            if (String.IsNullOrEmpty(nextPageUrl))
            {
                url = null;
                return true;
            }
            url = searchApi + nextPageUrl;
            return false;
        }

        private static TweetStored GetTweet(JObject obj)
        {
            JsonFieldExtractor extractor = new JsonFieldExtractor(obj);
            TweetStored tweet = new TweetStored
            {
                TweetId = extractor.GetFieldStringValue("id_str"),
                Date = ParseDate(extractor.GetFieldStringValue("created_at")),
                Source = extractor.GetFieldStringValue("source"),
                Text = extractor.GetFieldStringValue("text"),
                UserName = extractor.GetFieldStringValue("from_user")
            };
            return tweet;
        }

        private static DateTime ParseDate(string extractFrom)
        {
            extractFrom = extractFrom.Remove(extractFrom.Length - 6, 6);
            return DateTime.Parse(extractFrom);
        }

        private static string GetJson(string url)
        {
            WebRequest request = WebRequest.Create(url);
            request.ContentType = "application/json; charset=utf-8";
            string jsonToParse;
            try
            {
                using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        jsonToParse = reader.ReadToEnd();
                    }
                }
                return jsonToParse;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}